package com.sgb.jicai.view.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.sgb.jicai.R;
import com.sgb.jicai.databinding.ActivityMycenterMyJoinBinding;
import com.sgb.jicai.view.fragment.MyCenterMyJoinFactoryFragment;
import com.sgb.jicai.view.fragment.MyCenterMyJoinXufangFragment;
import com.sgb.jicai.viewmodel.MyCenterMyJoinModel;
import com.sgb.link.entity.EventConstant;
import com.swgk.core.base.AppActivity;
import com.swgk.core.util.DisplayUtil;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.jicai.event.JiCaiEventEntity;
import com.sgb.jicai.entity.JcCountEntity;
import com.swgk.core.recyclerview.adapter.MainHomePagerAdapter;
import com.swgk.core.util.SharedPreferenceUtil;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;

/**
 * 个人中心--我的加盟
 */
public class MyCenterMyJoinActivity extends AppActivity implements View.OnClickListener {

    MyCenterMyJoinModel model;
    ActivityMycenterMyJoinBinding binding;

    private List<List<String>> menuList = new ArrayList();
    private List<List<Fragment>> fragmentlist = new ArrayList<List<Fragment>>();
    private MainHomePagerAdapter adapter;
    private boolean misScrolled = false;

    //一级tab数据
    private List<PickSelectEntity> dataTabFirst;
    //二级tab数据
    private List<PickSelectEntity> dataTabSecond;

    private String searchWords;
    private int firstTabSelect;
    private String groupbuyMode = "1";

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, MyCenterMyJoinActivity.class);
        context.startActivity(intent);
    }
    @Override
    protected void initView() {
        super.initView();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_mycenter_my_join);
        model = new ViewModelProvider(this).get(MyCenterMyJoinModel.class);
        model.setActivity(MyCenterMyJoinActivity.this);
        binding.ivBack.setOnClickListener(this::onMultiClick);
        binding.tvSearch.setOnClickListener(this::onMultiClick);
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        if (companyNo.equals("") || companyNo.equals("0")) {
            //个人
            binding.tabLayout1.setVisibility(View.GONE);
            binding.viewPager.setNoScroll(true);
        } else {
            //公司
            binding.tabLayout1.setVisibility(View.VISIBLE);
            binding.viewPager.setNoScroll(false);
        }

        binding.editSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    searchWords = binding.editSearch.getText().toString().trim();
                    //调用Fragment的刷新
                    EventBus.getDefault().post(new JiCaiEventEntity(EventConstant.EVENT_JICAI_MY_CEN_AND_JOIN, searchWords));
                    hideKeyboard();
                }
                return false;
            }
        });
    }

    @Override
    protected void init() {
        super.init();
        model.getFirstTabDatas();
        getTabNum();
    }

    @Override
    public void onMultiClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_search) {
            searchWords = binding.editSearch.getText().toString().trim();
            //调用Fragment的刷新
            EventBus.getDefault().post(new JiCaiEventEntity(EventConstant.EVENT_JICAI_MY_CEN_AND_JOIN, searchWords));
            hideKeyboard();
        }
    }

    public void showEmptyView() {
        binding.coordinator.setVisibility(View.GONE);
        binding.emptyView.setVisibility(View.VISIBLE);
    }

    public void showTabView() {
        binding.coordinator.setVisibility(View.VISIBLE);
        binding.emptyView.setVisibility(View.GONE);
    }

    public void updateFirstTabData(List<PickSelectEntity> datas) {
        dataTabFirst = datas;
        updataTab();
    }

    private void updataTab() {
        for (int i = 0; i < dataTabFirst.size(); i++) {
            binding.tabLayout1.addTab(binding.tabLayout1.newTab());
            binding.tabLayout1.getTabAt(i).setText(dataTabFirst.get(i).getProjectscale());
            List tabSecondText = new ArrayList();
            List<Fragment> fragmentsList = new ArrayList<>();
            dataTabSecond = model.getSecondTabDatas();
            if (!dataTabFirst.get(i).getNo().equals("100")){
                dataTabSecond.add(new PickSelectEntity("4", "集采失败"));//供方发起不添加集采失败
            }
            for (int j = 0; j < dataTabSecond.size(); j++) {
                tabSecondText.add(dataTabSecond.get(j).getProjectscale());
                if (dataTabFirst.get(i).getNo().equals("100")) {//供方发起---单独的Fragment
                    fragmentsList.add(MyCenterMyJoinFactoryFragment.newInstance(dataTabFirst.get(i).getNo(), dataTabSecond.get(j).getNo()));
                } else {
                    fragmentsList.add(MyCenterMyJoinXufangFragment.newInstance(dataTabFirst.get(i).getNo(), dataTabSecond.get(j).getNo()));
                }
            }
            menuList.add(tabSecondText);
            fragmentlist.add(fragmentsList);
        }
        adapter = new MainHomePagerAdapter(getSupportFragmentManager(), menuList.get(0).toArray(new String[0]), fragmentlist.get(0));
        binding.viewPager.setAdapter(adapter);
        binding.tabLayout2.setupWithViewPager(binding.viewPager);
  /*      binding.tabLayout2.setTabMode(dataTabSecond.size() >= 4 ? TabLayout.MODE_SCROLLABLE : TabLayout.MODE_FIXED);*/
        //监听tabLayout1变化，根据变化相应刷新tabLayout2的内容
        binding.tabLayout1.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                firstTabSelect = position;
                groupbuyMode = dataTabFirst.get(position).getNo();
                getTabNum();
                binding.viewPager.setAdapter(new MainHomePagerAdapter(getSupportFragmentManager(), menuList.get(position).toArray(new String[0]), fragmentlist.get(position)));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        //监听viewPager的变化，在滑到最前或最后时，判断是否进行tabLayout1的切换
        binding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager.SCROLL_STATE_DRAGGING:
                        misScrolled = false;
                        break;
                    case ViewPager.SCROLL_STATE_SETTLING:
                        misScrolled = true;
                        break;
                    case ViewPager.SCROLL_STATE_IDLE:
                        if (!misScrolled) {
                            //滑动到最后一页继续往后滑
                            if (binding.viewPager.getCurrentItem() == binding.viewPager.getAdapter().getCount() - 1) {
                                int tabPosition = binding.tabLayout1.getSelectedTabPosition();
                                if (tabPosition != menuList.size() - 1) {//不是最后一个
                                    binding.tabLayout1.getTabAt(tabPosition + 1).select();
                                }
                            } else if (binding.viewPager.getCurrentItem() == 0) {  //滑动到第一页继续往前滑
                                int tabPosition = binding.tabLayout1.getSelectedTabPosition();
                                if (tabPosition != 0) {//不是第一个
                                    binding.tabLayout1.getTabAt(tabPosition - 1).select();
                                }
                            }
                        }
                        misScrolled = true;
                        break;
                }
            }
        });

        for (int i = 0; i < binding.tabLayout1.getTabCount(); i++) {
            TabLayout.Tab tab = binding.tabLayout1.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(getTabView(i));
            }
        }
        updateTabTextView(binding.tabLayout1.getTabAt(binding.tabLayout1.getSelectedTabPosition()), true);
        binding.tabLayout1.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                updateTabTextView(tab, true);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                updateTabTextView(tab, false);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    private View getTabView(int currentPosition) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.tab_item_textview, null);
        TextView textView = (TextView) view.findViewById(R.id.tv_tab_item_textview);
        textView.setTextColor(getResources().getColor(R.color.color_main_bg));
        textView.setTextSize(15);
        textView.setText(dataTabFirst.get(currentPosition).getProjectscale());
        return view;
    }

    private void updateTabTextView(TabLayout.Tab tab, boolean isSelect) {
        if (tab == null || tab.getCustomView() == null) return;
        if (isSelect) {
            //选中加粗
            TextView tabSelect = (TextView) tab.getCustomView().findViewById(R.id.tv_tab_item_textview);
            tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tabSelect.setTextColor(getResources().getColor(R.color.white));
            tabSelect.setTextSize(18);
            tabSelect.setText(tab.getText());
        } else {
            TextView tabUnSelect = (TextView) tab.getCustomView().findViewById(R.id.tv_tab_item_textview);
            tabUnSelect.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            tabUnSelect.setTextColor(getResources().getColor(R.color.color_main_bg));
            tabUnSelect.setTextSize(15);
            tabUnSelect.setText(tab.getText());
        }
    }

    public void getTabNum() {
        if (firstTabSelect != 2) {
            model.getMyGroupBuyListCount(groupbuyMode, searchWords);
        } else {
            model.getMyOfferBuyListCount(searchWords);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(JiCaiEventEntity event) {
        if (event.getCode() == EventConstant.EVENT_JICAI_TOP_REFRESH_VISIBLE) {
            // 返回顶部
            CoordinatorLayout.Behavior behavior =
                    ((CoordinatorLayout.LayoutParams) binding.appBarLayout.getLayoutParams()).getBehavior();
            if (behavior instanceof AppBarLayout.Behavior) {
                AppBarLayout.Behavior appBarLayoutBehavior = (AppBarLayout.Behavior) behavior;
                int topAndBottomOffset = appBarLayoutBehavior.getTopAndBottomOffset();
                if (topAndBottomOffset != 0) {
                    appBarLayoutBehavior.setTopAndBottomOffset(0);
                    binding.appBarLayout.setExpanded(true, true);
                }
            }
        } else if (event.getCode() == EventConstant.EVENT_JICAI_MYCENTER_XUFANG_FAQI_TABNUM) {//执行删除操作之后刷新顶部数量
            getTabNum();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        // 隐藏软键盘
        imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
    }

    public void setTabNum(List<JcCountEntity> numList) {
        if (null == numList || numList.size() == 0) {
            return;
        }
        // 刷新个数后根据当前展示的一级tab是第几个，显示对应的二级tab
        for (JcCountEntity entity : numList) {
            String num = " (" + (Integer.valueOf(entity.getCount()) > 99 ? "99+" : entity.getCount()) + ")";
            switch (Integer.valueOf(entity.getStatus())) {//012
                case 0:
                    setTabTitleSize(binding.tabLayout2.getTabAt(0), "全部" + num);
                    break;
                case 1:
                    setTabTitleSize(binding.tabLayout2.getTabAt(1), "集采中" + num);
                    break;
                case 2:
                    setTabTitleSize(binding.tabLayout2.getTabAt(2), "集采完成" + num);
                    break;
                case 4:
                    setTabTitleSize(binding.tabLayout2.getTabAt(3), "集采失败" + num);
                    break;
            }
        }
    }

    private void setTabTitleSize(TabLayout.Tab tab, String text) {
        if (null == tab) {//多个fragment已创建，但是懒加载时后面的页面还没有初始化tab
            return;
        }
        int start = text.indexOf("(");
        int end = text.length();
        SpannableString textSpan = new SpannableString(text);
        textSpan.setSpan(new AbsoluteSizeSpan(DisplayUtil.sp2px(this, 14)), 0, start, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        textSpan.setSpan(new AbsoluteSizeSpan(DisplayUtil.sp2px(this, 10)), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        tab.setText(textSpan);
    }

    public String getKeyWords() {
        String key = binding.editSearch.getText().toString().trim();
        return TextUtils.isEmpty(key) ? "" : key;
    }


}
